package com.emqx.auth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步线程池
 * @author zhangfutao
 */
@Component
@EnableAsync
public class ThreadConfig {

	@Bean("esOperateExecutor")
	public Executor ESOperateExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		//此方法返回可用处理器最大数量
		int core = Runtime.getRuntime().availableProcessors();
		executor.setCorePoolSize(core);//设置核心线程数
		executor.setMaxPoolSize(core * 2);//设置最大线程数
		executor.setKeepAliveSeconds(3);//除核心线程外的线程存活时间
		executor.setQueueCapacity(40);//如果传入值大于0，底层队列使用的是LinkedBlockingQueue,否则默认使用SynchronousQueue
		executor.setThreadNamePrefix("thread-es-");//线程名称前缀
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());//设置拒绝策略
		return executor;
	}
}
